package demo.util;

import com.alibaba.fastjson2.JSON;
import lombok.Getter;
import lombok.Setter;
import org.junit.Test;
import org.yaml.snakeyaml.Yaml;

import java.util.Collections;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * 普罗报警规则
 * <blockquote><pre>
 *        alert: InstanceDown
 *        expr: up{job="node"} == 0 and ON(instance) ping_loss_ratio{} == 1
 *        for: 1m
 *        labels:
 *          x_system: k8s_node
 *          x_service: "{{ $labels.cluster }}"
 *          x_target: "{{ $labels.instance }}"
 *        annotations:
 *          summary: "Instance Down"
 *          description: "{{ $labels.instance }} has been down for more than 1 minute"
 *          runbook_url: "http://your-wiki/runbooks/instance-down"
 *        dsRefer:
 * </pre><blockquote/>
 */
@Getter
@Setter
public class PrometheusAlertRule {

    public static final String LABEL_SYSTEM = "x_system";
    public static final String LABEL_SERVICE = "x_service";
    public static final String LABEL_TARGET = "x_target";

    private String alert;
    private String expr;
    private String duration;
    private Map<String, String> labels;
    private Map<String, String> annotations;
    /**
     * 关联的数据
     */
    private Set<String> dsRefer;

    public static PrometheusAlertRule from(String yamlContent) {
        if (yamlContent == null || yamlContent.isEmpty()) {
            return null;
        }
        PrometheusAlertRule vo = new PrometheusAlertRule();
        // 解析为 Map 结构
        Map<String, Object> data = new Yaml().load(yamlContent);
        vo.setAlert((String) data.get("alert"));
        vo.setExpr((String) data.get("expr"));
        vo.setDuration((String) data.get("for"));
        vo.setLabels((Map<String, String>) data.get("labels"));
        vo.setAnnotations((Map<String, String>) data.get("annotations"));
        String ds = (String) data.get("dsRefer");
        if (ds == null || ds.isEmpty()) {
            vo.setDsRefer(Collections.emptySet());
        } else {
            Set<String> dsRefer = Stream.of(ds.split(","))
                    .map(String::trim).filter(s -> !s.isEmpty())
                    .collect(Collectors.toSet());
            vo.setDsRefer(dsRefer);
        }
        return vo;
    }

    public String getLabelSystem() {
        return labels == null ? null : labels.get(LABEL_SYSTEM);
    }

    public String getLabelService() {
        return labels == null ? null : labels.get(LABEL_SERVICE);
    }

    public String getLabelTarget() {
        return labels == null ? null : labels.get(LABEL_TARGET);
    }

    public String getSummery(){
        return annotations == null ? "" : annotations.get("summary");
    }

    public String getDescription(){
        return annotations == null ? "" : annotations.get("description");
    }

    public String getRunbookUrl(){
        return annotations == null ? "" : annotations.get("runbook_url");
    }


    @Override
    public String toString() {
        return JSON.toJSONString(this);
    }

    @Test
    public void test(){
        String a = "alert: KafkaLagMore\n" +
                "expr: (sum(kafka_consumergroup_lag{env=\"prod\",service_line=\"future\",consumergroup=~\"future-biz-user-websocket-.*\", topic=\"execution_report\"}) by (consumergroup, topic)) > 100\n" +
                "for: 1m\n" +
                "labels:\n" +
                "  x_system: \"{{ $labels.service_line }}\"\n" +
                "  x_service: \"{{ $labels.topic }}\"\n" +
                "  x_target: \"{{ $labels.consumergroup }}\"\n" +
                "annotations:\n" +
                "  summary: \" S1[生产环境-核心Topic] 合约消息积压\"\n" +
                "  description: \"消费者[{{ $labels.consumergroup }}] 消费Topic[{{ $labels.topic }}] 积压 {{ $value }}条消息\"\n" +
                "dsRefer: vmcluster";
        PrometheusAlertRule vo = PrometheusAlertRule.from(a);
        System.out.println(vo);
    }

}
